package com.sdgakj.study.thread.pc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: Du Ronghong
 * @Description:
 * @Date: Created in 18:33 2018/8/28
 * @Modified By:
 */
public class Data {

    private int num;
    private int max=10;
    private Lock lock;
    private Condition producerCondition;
    private Condition consumerCondition;

    public Data(Lock lock, Condition producerCondition,Condition consumerCondition) {
        this.lock = lock;
        this.producerCondition = producerCondition;
        this.consumerCondition = consumerCondition;
    }

    public void remove(){
        lock.lock();
        try {
            if(num>0){
                num--;
                System.out.println(Thread.currentThread().getName()+"正在消费,剩余数量:"+num);
                consumerCondition.signalAll();
            }else{
                try {
                    producerCondition.await();
                    System.out.println(Thread.currentThread().getName()+"停止消费,等待生产");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            lock.unlock();
        }
    }

    public void add(){
        lock.lock();

        try {
            if(num<max){
                num++;
                System.out.println(Thread.currentThread().getName()+"正在生产,产品数量:"+num);
                producerCondition.signalAll();
            }else{
                try {
                    consumerCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            lock.unlock();
        }
    }
}
